package com.yuyang.wifi.utils;

import android.view.View;

import com.jakewharton.rxbinding.view.RxView;
import com.trello.rxlifecycle.LifecycleProvider;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by wangce on 16/1/14.
 */
public class RxUtil {

    public static Observable<Void> clickThrottle(View view) {
        return RxView.clicks(view).throttleFirst(1, TimeUnit.SECONDS);
    }

    public static Observable<Long> timer(long interval, TimeUnit timeUnit) {
        return Observable.interval(0,interval, timeUnit);
    }

    public static Observable<Long> timerToEnd(long interval, int countSeconds, TimeUnit timeUnit) {
        return timer(interval, timeUnit).take(countSeconds);
    }

    @Deprecated
    public static Observable<Long> countdown(final int countSeconds) {
        return timer(1L, TimeUnit.SECONDS).take(countSeconds + 1).map(new Func1<Long, Long>() {
            @Override
            public Long call(Long aLong) {
                return countSeconds -aLong;
            }
        }).observeOn(AndroidSchedulers.mainThread());
    }


    public static Observable<Long> countdown(LifecycleProvider lifecycleProvider, final int countSeconds) {

        return timer(1L, TimeUnit.SECONDS).take(countSeconds + 1).map(new Func1<Long, Long>() {
            @Override
            public Long call(Long aLong) {
                return countSeconds - aLong;
            }
        }).compose(lifecycleProvider.<Long>bindToLifecycle()).observeOn(AndroidSchedulers.mainThread());
    }

    public static <T> Observable.Transformer<T, T> applySchedulers() {
        return new Observable.Transformer<T, T>() {
            @Override
            public Observable<T> call(Observable<T> observable) {
                return observable.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    public static <T> Observable.Transformer<T, T> bindLifecycle(final LifecycleProvider lifecycleProvider) {
        return new Observable.Transformer<T, T>() {
            @Override
            public Observable<T> call(Observable<T> observable) {
                return observable.compose(lifecycleProvider.<T>bindToLifecycle());
            }
        };
    }


    public static <T> Observable.Transformer<T, T> bindLifecycleAndApplySchedulers(final LifecycleProvider lifecycleProvider) {
        return new Observable.Transformer<T, T>() {
            @Override
            public Observable<T> call(Observable<T> observable) {
                return observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).compose(lifecycleProvider.<T>bindToLifecycle());
            }
        };
    }



}
